﻿#include "emp_dialog.h"
#include "ui_emp_dialog.h"
#include "basal_sql.h"
#include <QLabel>
#include <QMessageBox>
#include <QDebug>
#include <QRegExp>
//超市员工管理界面
emp_dialog::emp_dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::emp_dialog)
{
    //见cash_produce_dialog.cpp
    ui->setupUi(this);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->editName->setFocus();

    QIntValidator *validator = new QIntValidator(this);
    ui->editCell->setValidator(validator);
    ui->editPassword->setValidator(validator);

    //正则表达式限制输入格式（不用管）
    QRegExp regx("[a-zA-Z]+$");
    QValidator *validator1 = new QRegExpValidator(regx, ui->editName);
    ui->editName->setValidator(validator1);

    ui->tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); //取消水平滚动条
}

emp_dialog::~emp_dialog()
{
    delete ui;
}

//页面初始化显示信息
void emp_dialog::showEvent(QShowEvent *)
{
    sqlite3 *pDb;
    if(sqlite3_open("./supermarket.db", &pDb)==SQLITE_OK){
        QString sql="select * from employee order by e_id DESC;";
        sqlite3_stmt *pStmt;
        if(sqlite3_prepare(pDb, sql.toStdString().c_str(), sql.length(), &pStmt, NULL) == SQLITE_OK){
            while(sqlite3_step(pStmt) == SQLITE_ROW){
                const unsigned char *pId = sqlite3_column_text(pStmt, 0);
                const unsigned char *pName = sqlite3_column_text(pStmt, 1);
                const unsigned char *pGender = sqlite3_column_text(pStmt, 2);
                const unsigned char *pCell = sqlite3_column_text(pStmt, 3);
                const unsigned char *pAddress = sqlite3_column_text(pStmt, 4);
                const unsigned char *pPass = sqlite3_column_text(pStmt, 5);

                QTableWidgetItem *pIdItem = new QTableWidgetItem((char *)pId);
                QTableWidgetItem *pNameItem = new QTableWidgetItem((char *)pName);
                QTableWidgetItem *pGenderItem = new QTableWidgetItem((char *)pGender);
                QTableWidgetItem *pAddressItem = new QTableWidgetItem((char *)pAddress);
                QTableWidgetItem *pCellItem = new QTableWidgetItem((char *)pCell);
                QTableWidgetItem *pPassItem = new QTableWidgetItem((char *)pPass);

                ui->tableWidget->insertRow(0);

                ui->tableWidget->setItem(0, 0, pIdItem);
                ui->tableWidget->setItem(0, 1, pNameItem);
                ui->tableWidget->setItem(0, 2, pGenderItem);
                ui->tableWidget->setItem(0, 3, pAddressItem);
                ui->tableWidget->setItem(0, 4, pCellItem);
                ui->tableWidget->setItem(0, 5, pPassItem);
            }
        }
    }


}

//添加员工按钮
void emp_dialog::on_pushButton_clicked()
{
    QString eName = ui->editName->text();
    QString ePassWord = ui->editPassword->text();
    QString eAddr = ui->editAdress->text();
    QString eCell = ui->editCell->text();
    QString eGender = ui->comboBox->currentText();
    //进行员工信息输入提示之类的功能（主要是使用errorLabel来提示用户操作）
    if(eName.isEmpty())
            {
                ui->errorLabel->setText("请输入员工名!");
                ui->editName->setFocus();
                return;
            }
            else if(eGender == "")
            {
                ui->errorLabel->setText("请选择性别!");
                ui->comboBox->setFocus();
                return;
            }
            else if(eCell.isEmpty())
            {
                ui->errorLabel->setText("请输入手机号!");
                ui->editCell->setFocus();
                return;
            }
            else if(eAddr.isEmpty())
            {
                ui->errorLabel->setText("请输入家庭住址!");
                ui->editAdress->setFocus();
                return;
            }
            else if(ePassWord.isEmpty())
            {
                ui->errorLabel->setText("请输入登录密码!");
                ui->editPassword->setFocus();
                return;
            }

        QSqlQuery query;
        //判断员工是否存在
        query.exec(tr("select e_name from employee"));
        bool hasEmp = false;
        while(query.next())
            {
                if(query.value(0).toString() == ui->editName->text())
                {
                    hasEmp = true;
                    break;
                }
            }
        if(hasEmp) //如果已经有了员工
            {
                int r = QMessageBox::question(this, tr("警告"), tr("该员工已经存在，是否强制添加？"), QMessageBox::No | QMessageBox::Yes);
                if(r == QMessageBox::No)
                {
                    ui->editName->selectAll();
                    ui->editName->setFocus();
                    return;
                }
            }

        //对数据库进行操作
        QString sql = "insert into employee(e_name,e_gender,e_cell,e_adress,e_password) "
                      "values('" +eName+ "','" +eGender+ "','" +eCell+ "','" +eAddr+ "','" +ePassWord+ "')";
        if(query.exec(sql)){
            while(ui->tableWidget->rowCount()){
                ui->tableWidget->removeRow(0);
            }
            emp_dialog::showEvent(NULL);

            //提高用户与系统的交互度（书写格式不必理解，大概知道就好）
            QMessageBox msgBox;
            msgBox.setText("添加成功！");
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
                    msgBox.setWindowTitle(tr("提示"));
                    msgBox.setButtonText(QMessageBox::Yes, tr("添加下一人"));
                    msgBox.setButtonText(QMessageBox::No, tr("返回主界面"));
                    msgBox.setDefaultButton(QMessageBox::No);
                    int ret = msgBox.exec();
                    if(ret == QMessageBox::Yes)     //继续添加下一条
                    {
                        ui->editName->clear();
                        ui->editPassword->clear();
                        ui->editAdress->clear();
                        ui->editCell->clear();
                        ui->comboBox->setCurrentText(" ");
                        ui->editName->setFocus();
                    }
                    else
                    {
                        this->accept();
                    }
            query.exec(QString("insert into user(username, password, userstyle) "
                               "values('" +eName+ "','" +ePassWord+ "','2')"));
        }
}

//删除按钮的实现（操作数据库）
void emp_dialog::on_pushButton_2_clicked()
{
    int row = ui->tableWidget->currentRow();
    if(row >= 0) {
        QTableWidgetItem *pIdItem = ui->tableWidget->item(row, 0);
        QString id = pIdItem->text();
        sqlite3 *pDb;
                 if(sqlite3_open("./supermarket.db", &pDb)!=SQLITE_OK) return;
                 QString sql = "delete from employee where e_id ='" +id+ "';";
                 char *errmsg;
                 if(sqlite3_exec(pDb,sql.toStdString().c_str(), NULL, NULL, &errmsg) == SQLITE_OK){
                     ui->tableWidget->removeRow(row);
                 }
                 // qDebug()<<"def "<<endl;
                 sqlite3_close(pDb);
    }
}
